let handler = {
  37(arr) {
    _2048(arr);
    return arr;
  },
  38(arr) {
    arr = rotateRight(arr, 3);
    _2048(arr);
    arr = rotateRight(arr, 1);
    return arr;
  },
  39(arr) {
    arr = rotateRight(arr, 2);
    _2048(arr);
    arr = rotateRight(arr, 2);
    return arr;
  },
  40(arr) {
    arr = rotateRight(arr, 1);
    _2048(arr);
    arr = rotateRight(arr, 3);
    return arr;
  },
};
//顺时针旋转 默认一次
function rotateRight(arr, num = 1) {
  let row = arr.length,
    col = arr[0].length;
  while (num--) {
    let newArr = Array.from({ length: row }, (item) => (item = []));
    for (let j = 0; j < col; j++) {
      for (let i = row - 1; i >= 0; i--) {
        newArr[j].push(arr[i][j]);
      }
    }
    arr = newArr;
  }
  return arr;
}
//left 只能处理一维数组 遍历二维数组 执行left
function _2048(arr) {
  for (let i in arr) {
    arr[i] = left(arr[i]);
  }
  return arr;
}

//向左合并
function left(arr) {
  let len = arr.length;
  let temp = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== 0) {
      let j = i + 1;
      while (arr[j] === 0) {
        j++;
      }
      if (arr[i] !== arr[j]) {
        temp.push(arr[i]);
      } else {
        temp.push(arr[i] * 2);
        i = j;
      }
    }
  }
  //末尾空余的地方添加0  [2,2,4,8]=>[4,4,8]
  while (temp.length < len) {
    temp.push(0);
  }
  return temp;
}

//添加两个随机2
function random(arr) {
  let len = arr.length;
  let x = parseInt(Math.random() * len);
  let y = parseInt(Math.random() * len);
  let count = 2;
  //后面没有空格子添加随机数 通过flag判断
  let flag = arr.some((item) => item.includes(0));
  while (count-- && flag) {
    while (arr[x][y] !== 0) {
      x = parseInt(Math.random() * len);
      y = parseInt(Math.random() * len);
      // console.log(len);
      // console.log(x, y);
      // console.log(arr[x][y]);
    }
    arr[x][y] = 2;
    flag = arr.some((item) => item.includes(0));
  }
  return arr;
}

export { random, handler };
